package Audio
{
	import Config.GameConfig;
	
	import flash.utils.Dictionary;

	public class SoundScene
	{
		public static var ss:SoundScene;
		
		private var sounds:Dictionary;
		
		public var channels:Array;
		
		public var toSyncRemoved:Boolean=false;
		
		public function SoundScene()
		{
			super();
			sounds=new Dictionary();
			channels=new Array();
			ss=this;
		}
		public function update():void
		{
			for each(var channel:GameSoundChannel in channels)
			{
				channel.update();
			}
			if(toSyncRemoved)
			{
				syncRemoved();
				toSyncRemoved=false;
			}
		}
		public function play(gameSound:GameSound):void
		{
			var channel:GameSoundChannel=new GameSoundChannel();
			channel.ss=this;
			channel.sound=gameSound;
			if(gameSound.isMusic)
			{
				channel.sc = gameSound.sound.play(gameSound.startTime,GameConfig.maxValue);
			}
			else
			{
				channel.sc = gameSound.sound.play();
			}
			channel.length=gameSound.sound.length;
			channel.update();
			channels.push(channel);
		}
		public function stop(soundName:String,fade:Boolean=true):void
		{
			for each(var chanel:GameSoundChannel in channels)
			{
				if(chanel.sound.name==soundName)
				{
					if(fade)
					{
						chanel.stop();
					}
					else
					{
						chanel.remove();
					}
				}
			}
		}
		public function addSound(sound:GameSound):void
		{
			sounds[sound.name]=sound;
		}
		public function getSound(soundName:String):GameSound
		{
			return sounds[soundName];
		}
		private function syncRemoved():void
		{
			channels = channels.filter(function (chanel:GameSoundChannel, index:int, arr:Array):Boolean{
				return !chanel.removed;
			});
		}
	}
}